import { AuthContext } from "@/App";
import { useContext, useEffect, useReducer, useState } from "react";
import { toast } from "sonner";
// import { useNavigate } from "react-router-dom";
import axios from "../utils/axios";
import { useNavigate } from "react-router-dom";

// import { cn } from "@/lib/utils";

// interface NavbarProps {
//   user: {
//     name: string;
//     avatar: string;
//     role: string;
//   };
//   unreadCount: number;
//   showNotifications: boolean;
//   setShowNotifications: (value: boolean) => void;
//   showUserMenu: boolean;
//   setShowUserMenu: (value: boolean) => void;
//   handleLogout: () => void;
// }

export default function Navbar() {
  const [showNotifications, setShowNotifications] = useState(false);
  const [showUserMenu, setShowUserMenu] = useState(false);
  const [unreadCount, setUnreadCount] = useState(0);


  const { logout } = useContext(AuthContext);
  const navigate = useNavigate();
  const [userData, setUserData] = useState({
    name: "",
    avatar: "",
    role: ""
  });

  const handleLogout = async () => {
    try {
      // 先调用后端退出接口
      await axios.post('/api/logout', {}, {
        withCredentials: true
      });

      // 然后执行前端退出逻辑
      logout();
      toast.success("已退出登录");
      navigate("/login");
    } catch (error) {
      console.error('退出登录失败:', error);
      toast.error('退出登录失败');
    }
  };
  // 添加获取用户数据的函数
  const fetchUserData = async () => {
    try {
      const response = await axios.get('/api/v1/user', {
        withCredentials: true
      });
      setUserData(response.data);
    } catch (error) {
      console.error('获取用户数据失败:', error);
    }
  };

  useEffect(() => {
    fetchUserData();
  });

  return (
    <div className="flex h-15 items-center justify-between bg-[#673AB7] px-6 py-3 text-white">
      <div className="flex items-center">
        <h1 className="text-lg font-bold">云上医疗</h1>
      </div>
      <div className="flex items-center space-x-4">
        <div className="relative">
          <button
            onClick={() => setShowNotifications(!showNotifications)}
            className="relative p-2"
          >
            <i className="fa-regular fa-bell text-xl"></i>
            {unreadCount > 0 && (
              <span className="absolute -right-1 -top-1 flex h-5 w-5 items-center justify-center rounded-full bg-red-500 text-xs">
                {unreadCount}
              </span>
            )}
          </button>
          {showNotifications && (
            <div className="absolute right-0 top-full mt-2 w-64 rounded-md bg-white p-3 shadow-lg">
              <h3 className="mb-2 text-sm font-semibold text-gray-800">通知</h3>
              <div className="space-y-2">
                {unreadCount > 0 ? (
                  <p className="text-sm text-gray-600">您有{unreadCount}条未读通知</p>
                ) : (
                  <p className="text-sm text-gray-600">暂无新通知</p>
                )}
              </div>
            </div>
          )}
        </div>
        <div className="relative">
          <button
            onClick={() => setShowUserMenu(!showUserMenu)}
            className="flex items-center space-x-2"
          >
            <img
              src={userData.avatar}
              alt={userData.name}
              className="h-8 w-8 rounded-full object-cover"
            />
            <span>{userData.name}</span>
          </button>
          {showUserMenu && (
            <div className="absolute right-0 top-full mt-2 w-48 rounded-md bg-white p-2 shadow-lg">
              <div className="p-2 text-sm text-gray-800">
                <p className="font-medium">{userData.name}</p>
                <p className="text-xs text-gray-500">{userData.role}</p>
              </div>
              <div className="border-t border-gray-200"></div>
              <button
                onClick={() => navigate('/profile')}
                className="block w-full px-4 py-2 text-left text-sm text-gray-700 hover:bg-gray-100"
              >
                个人主页
              </button>
              <button
                onClick={handleLogout}
                className="block w-full px-4 py-2 text-left text-sm text-gray-700 hover:bg-gray-100"
              >
                退出登录
              </button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
